package com.fang.system.io.mocknetty;

import java.io.IOException;
import java.net.StandardSocketOptions;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description TODO
 * @date 2022/7/15 3:24 下午
 **/
public class ServerAcceptor implements Handler {
    private EventLoopGroup worker;
    private ServerSocketChannel server;

    public ServerAcceptor(EventLoopGroup worker, ServerSocketChannel channel) {
        this.worker = worker;
        this.server = channel;
    }

    @Override
    public void doRead() {
        try {
            EventLoop eventLoop = worker.chooser();
            SocketChannel client = server.accept();
            client.configureBlocking(false);
            client.setOption(StandardSocketOptions.TCP_NODELAY, true);
            ClientReader clientReader = new ClientReader(client);
            eventLoop.execute(() -> {
                System.out.println("socket send to " + eventLoop.eventLoopName + " client port:" + client.socket().getPort());
                try {
                    client.register(eventLoop.selector, SelectionKey.OP_READ, clientReader);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
